﻿using System;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Me.Amon.Da.Db;
using Me.Amon.Da.Db.OMS;
using Me.Amon.M;
using Me.Amon.POS.C;
using Me.Amon.Util;
using Me.Amon.WMS.C;

namespace Me.Amon.POS
{
    public partial class UpdateSpu : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            var user = WebUtil.CurrentUser(Session);
            if (user.Rank < IUser.LEVEL_01)
            {
                Response.Redirect(IEnv.HOME_PAGE);
                return;
            }

            var cat = Request["cat"];
            if (!CharUtil.IsValidateHash(cat))
            {
                cat = "0";
            }

            var dba = new RDBEngine();
            ListCat(dba, user, cat);

            dba.Reset();
            ListBrand(dba, user.CorpId);

            var spu = Request["spu"];
            if (CharUtil.IsValidateHash(spu))
            {
                dba.Reset();
                ReadSpu(dba, user.CorpId, spu);
            }
        }

        #region 事件处理
        protected void BtUpdateSpu_Click(object sender, EventArgs e)
        {
            SaveSpu();
        }

        protected void BtCancelSpu_Click(object sender, EventArgs e)
        {
            var node = TvCats.SelectedNode;
            if (node == null)
            {
                return;
            }

            Response.Redirect("~/POS/Spus.aspx?cat=" + node.Value);
        }
        #endregion

        #region 目录
        private void ListCat(RDBEngine dba, MUser user, string cat)
        {
            var root = new TreeNode();
            root.Value = "0";
            root.Text = "商品类别";
            TvCats.Nodes.Add(root);
            root.Selected = (cat == root.Value);

            dba.AddTable(DCat.TABLE);
            dba.AddColumn(DCat.ID);
            dba.AddColumn(DCat.NAME);
            dba.AddWhere(DCat.PID, "0");
            dba.AddWhere(DCat.CORP_ID, user.Code);
            dba.AddWhere(DCat.STATUS, CCat.STATUE_ENABLED.ToString(), false, false);

            foreach (DataRow row in dba.ExecuteSelect().Rows)
            {
                var node = new TreeNode();
                node.Value = "" + row[DCat.ID];
                node.Text = "" + row[DCat.NAME];
                root.ChildNodes.Add(node);
                node.Selected = (cat == node.Value);

                LoadCat(dba, node, cat);
            }
        }

        private void ListBrand(RDBEngine dba, string corp)
        {
            dba.AddTable(DSpuBrand.TABLE);
            dba.AddColumn(DSpuBrand.ID);
            dba.AddColumn(DSpuBrand.NAME);
            dba.AddWhere(DSpuBrand.CORP_ID, corp);
            dba.AddWhere(DSpuBrand.STATUS, CSpuBrand.STATUE_ENABLED.ToString(), false);

            var dt = dba.ExecuteSelect();
            CbBrand.DataSource = dt;
            CbBrand.DataValueField = DSpuBrand.ID;
            CbBrand.DataTextField = DSpuBrand.NAME;
            CbBrand.DataBind();

            CbBrand.Items.Insert(0, new ListItem { Text = "无", Value = "0" });
        }

        private void LoadCat(RDBEngine dba, TreeNode root, string cat)
        {
            dba.Reset();
            dba.AddTable(DCat.TABLE);
            dba.AddColumn(DCat.ID);
            dba.AddColumn(DCat.NAME);
            dba.AddWhere(DCat.PID, root.Value);
            dba.AddWhere(DCat.STATUS, CCat.STATUE_ENABLED.ToString(), false, false);

            foreach (DataRow row in dba.ExecuteSelect().Rows)
            {
                var node = new TreeNode();
                node.Value = "" + row[DCat.ID];
                node.Text = "" + row[DCat.NAME];
                root.ChildNodes.Add(node);
                node.Selected = (cat == node.Value);

                LoadCat(dba, node, cat);
            }
        }
        #endregion

        private void ReadSpu(RDBEngine dba, string corp, string spu)
        {
            dba.AddTable(DSpu.TABLE);
            dba.AddWhere(DSpu.CORP_ID, corp);
            dba.AddWhere(DSpu.ID, spu);
            var dt = dba.ExecuteSelect();
            if (dt.Rows.Count != 1)
            {
                return;
            }

            DataRow row = dt.Rows[0];
            HdId.Value = spu;
            TbCode.Text = "" + row[DSpu.CODE];
            CbBrand.SelectedValue = "" + row[DSpu.BRAND_ID];
            TbName.Text = "" + row[DSpu.NAME];
            TbUom.Text = "" + row[DSpu.UOM_ID];
            TbHypy.Text = "" + row[DSpu.HYPY];
            TbSpec.Text = "" + row[DSpu.SPEC];
            TbMode.Text = "" + row[DSpu.MODE];
            TbMaxInv.Text = "" + row[DSpu.MAX_INV];
            TbMinInv.Text = "" + row[DSpu.MIN_INV];
            TbVdY.Text = "" + row[DSpu.VALID_YEAR];
            TbVdM.Text = "" + row[DSpu.VALID_MONTH];
            TbVdd.Text = "" + row[DSpu.VALID_DAY];
            CkVip.Checked = 1 == (int)row[DSpu.IS_VIP];
            CkPro.Checked = 1 == (int)row[DSpu.IS_PRO];
            CkStatus.Checked = CSpu.STATUS_DISABLED == (int)row[DSpu.STATUS];
            CkPoint.Checked = 1 == (int)row[DSpu.HAS_POINT];

            dba.Reset();
            dba.AddTable(DSpuBarcode.TABLE);
            dba.AddColumn(DSpuBarcode.BARCODE);
            dba.AddWhere(DSpuBarcode.SPU_ID, spu);
            dba.AddSort(DSpuBarcode.DISPLAY, true);
            var buf = new StringBuilder();
            foreach (DataRow tmp in dba.ExecuteSelect().Rows)
            {
                buf.Append(tmp[DSpuBarcode.BARCODE]).Append(',');
            }
            if (buf.Length > 0)
            {
                TbBars.Text = buf.ToString(0, buf.Length - 1);
            }
        }

        private void SaveSpu()
        {
            LlErr.Text = "";
            var id = HdId.Value;

            var node = TvCats.SelectedNode;
            if (node == null)
            {
                LlErr.Text = "请选择商品分类！";
                return;
            }

            var name = TbName.Text.Trim();
            if (!WebUtil.IsValid(name, "商品名称", CSpu.NAME, LlErr))
            {
                return;
            }

            var vdy = int.Parse(TbVdY.Text);
            if (vdy < 0)
            {
                LlErr.Text = "有效期年不能小于0！";
                return;
            }

            var vdm = int.Parse(TbVdM.Text);
            if (vdm < 0)
            {
                LlErr.Text = "有效期月不能小于0！";
                return;
            }

            var vdd = int.Parse(TbVdd.Text);
            if (vdd < 0)
            {
                LlErr.Text = "有效期日不能小于0！";
                return;
            }

            var hypy = TbHypy.Text.Trim();

            var mode = TbMode.Text.Trim();
            var spec = TbSpec.Text.Trim();

            var user = WebUtil.CurrentUser(Session);

            var dba = new RDBEngine();

            bool isUpdate = CharUtil.IsValidateHash(id);
            string code = "";
            if (!isUpdate)
            {
                code = KeyUtil.NextSpuKey(dba, user.CorpId);
                dba.Reset();
            }

            dba.AddTable(DSpu.TABLE);
            dba.AddParam(DSpu.BRAND_ID, CbBrand.SelectedValue);
            dba.AddParam(DSpu.NAME, name);
            dba.AddParam(DSpu.HYPY, hypy.ToUpper());
            dba.AddParam(DSpu.MODE, mode);
            dba.AddParam(DSpu.SPEC, spec);
            dba.AddParam(DSpu.UOM_ID, "0");
            dba.AddParam(DSpu.CAT_ID, node.Value);
            dba.AddParam(DSpu.MERCHANT_ID, "");
            dba.AddParam(DSpu.MERCHANT_CODE, "");
            dba.AddParam(DSpu.MERCHANT_NAME, "");
            dba.AddParam(DSpu.MAX_INV, 0);
            dba.AddParam(DSpu.MIN_INV, 0);
            dba.AddParam(DSpu.VALID_YEAR, vdy);
            dba.AddParam(DSpu.VALID_MONTH, vdm);
            dba.AddParam(DSpu.VALID_DAY, vdd);
            dba.AddParam(DSpu.IS_VIP, CkVip.Checked ? 1 : 0);
            dba.AddParam(DSpu.IS_PRO, CkPro.Checked ? 1 : 0);
            dba.AddParam(DSpu.HAS_POINT, CkPoint.Checked ? 1 : 0);
            dba.AddParam(DSpu.STATUS, CkStatus.Checked ? CSpu.STATUS_DISABLED : CSpu.STATUE_ENABLED);
            dba.AddParam(DSpu.UPDATE_TIME, DSpu.NOW, false);
            dba.AddParam(DSpu.UPDATE_USER, user.UserId);
            dba.AddParam(DSpu.CORP_ID, user.CorpId);
            if (CharUtil.IsValidateHash(id))
            {
                dba.AddWhere(DSpu.ID, id);
                dba.AddUpdateBatch();

                SaveBar(dba, id, user.UserId, true);

                dba.ExecuteBatch();

                Response.Redirect("~/POS/Spus.aspx?cat=" + node.Value);
            }
            else
            {
                id = HashUtil.UtcTimeInHex();
                dba.AddParam(DSpu.ID, id);
                dba.AddParam(DSpu.CODE, code);
                dba.AddParam(DSpu.CREATE_TIME, DSpu.NOW, false);
                dba.AddParam(DSpu.CREATE_USER, user.UserId);
                dba.ExecuteInsert();

                SaveBar(dba, id, user.UserId, false);

                ShowDef();
            }
        }

        private void SaveBar(RDBEngine dba, string spu, string user, bool clear)
        {
            if (clear)
            {
                dba.Reset();
                dba.AddTable(DSpuBarcode.TABLE);
                dba.AddWhere(DSpuBarcode.SPU_ID, spu);
                dba.AddDeleteBatch();
            }

            int idx = 0;
            foreach (var bar in Regex.Split(TbBars.Text, "[^\\w]"))
            {
                dba.Reset();
                dba.AddTable(DSpuBarcode.TABLE);
                dba.AddParam(DSpuBarcode.SPU_ID, spu);
                dba.AddParam(DSpuBarcode.BARCODE, bar);
                dba.AddParam(DSpuBarcode.DISPLAY, idx++);
                dba.AddParam(DSpuBarcode.STATUS, CSpuBarcode.STATUE_ENABLED);
                dba.AddParam(DSpuBarcode.CREATE_TIME, DSpuBarcode.NOW, false);
                dba.AddParam(DSpuBarcode.CREATE_USER, user);
                dba.AddInsertBatch();
            }
        }

        private void ShowDef()
        {
            HdId.Value = "";
            TbCode.Text = "";
            CbBrand.SelectedIndex = 0;
            TbName.Text = "";
            TbHypy.Text = "";
            TbMode.Text = "";
            TbSpec.Text = "";
            TbMaxInv.Text = "0";
            TbMinInv.Text = "0";
            TbVdY.Text = "0";
            TbVdM.Text = "0";
            TbVdd.Text = "0";
            TbBars.Text = "";
            TbUom.Text = "";
        }
    }
}